package com.polaris.live.popup.party

import android.content.Context
import android.text.Editable
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupRoomNameBinding
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.translation.R.string

/**
 *  房间名修改
 * @author Created by 天晴 on 2024/2/27 19:18
 * @since 1.0.0
 **/
class RoomNameMessagePopup(
    context: Context,
    private val mName: String? = null,
    private val onSave: (data: String) -> Unit,
) : CenterPopupView(context) {

    private lateinit var mBinding: PopupRoomNameBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_room_name
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupRoomNameBinding.bind(popupImplView)

        mBinding.edit.addTextChangedListener(textWatcher)
        val text = mName ?: StringUtils.getString(string.please_input_room_name)
        mBinding.edit.text = Editable.Factory.getInstance().newEditable(text)
        setTextCount(text.length)
        mBinding.edit.setSelection(text.length)
        mBinding.save.setOnSingleClickListener {
            val message = mBinding.edit.text?.toString()?.trim() ?: ""
            if (message.isNotEmpty() && message.isNotBlank()) {
                dismiss()
                onSave.invoke(message)
            } else {
                ToastGravity.showGravity(StringUtils.getString(string.name_spaces_empty))
            }
        }
    }

    private val textWatcher = object : TextWatcherAdapter() {
        override fun afterTextChanged(s: Editable?) {
            s?.let {
                val text = it.toString()
                setTextCount(text.length)
            }
        }
    }

    private fun setTextCount(count: Int) {
        mBinding.tipCount.text = "$count/20"
    }
}